import matplotlib
import time
import textwrap
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
from PIL import Image
from plottable import ColumnDefinition, ColDef, Table





def get_result(df_desc):
    df_as_list = df_desc.values.tolist()
    result_list = [f"{row[0]}: {row[1]}" for row in df_as_list]
    # 打印结果
    combined_string = ""
    for index, item in enumerate(result_list):
        if index==0:
            combined_string += "结论：" + "\n"
            combined_string += "    "+item + "\n"  # 添加换行符以分隔每个字符串
        else:
            if index==len(result_list)-1:
                combined_string += "    "+item
            else:
                combined_string += "    "+item + "\n"

    print(combined_string)
    return  combined_string

def update_status(value):
    if value == '1':
        return '通过'
    elif value == '0':
        return '未通过'

def get_pic1(faultid,faultobj,faultdesp,test_desp,pass_desc_str,job_isPass,savepath,jobid):
    # 初始化一个DataFrame并定义列名
    df = pd.DataFrame(columns=['clumn', 'content'])

    # 使用.iloc[]来设置行数据
    df.loc[0] = ['测试故障Case', "FaultID: "+faultid+" FaultObj: "+faultobj]
    df.loc[1] = ['故障名称描述', faultdesp]
    df.loc[2] = ['测试方法', test_desp]
    df.loc[3] = ['子功能通过情况', pass_desc_str]
    df.loc[4] = ['测试结果', job_isPass]
    df.set_index('clumn', inplace=True)
    print(df)
    group_str="FaultId:"+faultid+"  FaultObj:"+faultobj+"  功能测试"

    fig, ax = plt.subplots(figsize=(10, 8))
    tab = Table(df, column_definitions=[
                                        ColumnDefinition(name="clumn",  border="both",width=2,group=group_str, cmap=matplotlib.cm.tab20, text_cmap=matplotlib.cm.Reds, title="",textprops={"ha": "center",'wrap': True,'fontfamily': 'Microsoft YaHei'}),
                                        ColumnDefinition(name="content",  border="both",width=10,group=group_str, cmap=matplotlib.cm.tab20, text_cmap=matplotlib.cm.Reds, title="",textprops={"ha": "left",'wrap': True,'fontfamily': 'Microsoft YaHei'})
                                        ],
                row_dividers=True, odd_row_color="#f0f0f0", even_row_color="#e0f6ff",footer_divider=True,
    col_label_divider_kw={"linewidth": 1, "linestyle": "solid"},
    column_border_kw = {"linewidth": 1, "linestyle": "-"},
    footer_divider_kw= {"linewidth": 1, "linestyle": "-"}
                )
    #设置字体大小：
    tab.rows[0].set_fontsize(6)
    tab.rows[1].set_fontsize(6)
    tab.rows[2].set_fontsize(6)
    tab.rows[3].set_fontsize(5)
    tab.rows[4].set_fontsize(6)
    tab.rows[3].set_facecolor("grey")
    tab.rows[4].set_fontcolor("red")

    # 调整上边距
    # plt.subplots_adjust(top=0.6)  # 设置上边距为整个图像高度的90%
    # 保存图片
    plt.rcParams['font.sans-serif'] = ["SimHei"]
    plt.savefig(savepath + 'pic1_' + jobid+"_"+faultid+"_"+faultobj+ '.png', dpi=300, bbox_inches='tight')
    plt.close()

def virsul_step2(jobid,savepath):
    df = pd.read_pickle(savepath + 'data_detail_'+ jobid + '.pkl')
    faultid_list= df[['faultid', 'faultobj','faultdesp','test_desp']].values.tolist()
    list_id=[]
    for row in faultid_list:
        faultid=row[0]
        faultobj=row[1]
        # faultdesp = row[2]
        # test_desp = row[3]
        st=faultid+"#"+faultobj
        list_id.append(st)
    list_set=set(list_id)
    #获取结论需要的数据：
    for row in list_set:
        arr=row.split("#")
        faultid=arr[0]
        faultobj = arr[1]

        df_result = df[df['faultid'] == faultid][df['faultobj'] ==faultobj]
        df_function_list=df_result[["functionname","faultdesp","description","test_desp"]].values.tolist()
        faultdesp=df_function_list[0][1]
        test_desp = textwrap.fill(df_function_list[0][3], width=50)
        df_description = df_result[["functionname", "description"]]
        df_description_list=df_description.values.tolist()
        pass_desc_str=""
        for row in df_description_list:
            functionname=row[0]
            description =row[1]
            pass_desc_str+=functionname+":    "+description+"\n"
        print(pass_desc_str)
        df_job_isPass = df_result[["job_isPass"]]
        df_job_isPass['job_isPass'] = df_job_isPass['job_isPass'].apply(update_status)
        df_job_isPass_list = df_job_isPass.values.tolist()
        job_isPass = df_job_isPass_list[0][0]
        get_pic1(faultid,faultobj,faultdesp,test_desp,pass_desc_str,job_isPass,savepath,jobid)


if __name__ == '__main__':
    jobid = '2023110812'
    # windows路径
    savepath = './csv/'

    virsul_step2(jobid,savepath)













